/**
 * Created by fwj on 15-12-25.
 */

$(function () {
    $('#id-input-file-2').ace_file_input({
        no_file: '未选择任何文件',
        btn_choose: '批量处理',
        btn_change: '重新选择',
        droppable: false,
        onchange: null,
        thumbnail: false //| true | large
        //whitelist:'gif|png|jpg|jpeg'
        //blacklist:'exe|php'
        //onchange:''
        //
    });
});
//function checkStatus(s, x) {
//    var id = $("#kerber_id_update").val();
//    if (s == 0) {
//        layer.confirm('是否确定开启认证?', {icon: 3, title: '提示'}, function (index) {
//            $.ajax({
//                type: 'post',
//                url: "user/open_att.do",
//                data: {"id": id},
//                error: function (XMLHttpRequest, textStatus, errorThrown) {
//                    alert(textStatus);
//                },
//                success: function (data) {
//                    if (data.success) {
//                        var message = data.data.message;
//                        if (data.data.type == 'error') {
//                            layer.alert(message);
//                        } else {
//                            layer.alert(message, function (index) {
//                                $("#close").attr("disabled", true);
//                                layer.close(index);
//                            });
//                        }
//                    }
//                }
//            })
//            layer.close(index);
//        });
//
//    } else {
//        layer.confirm('是否确定关闭认证?', {icon: 3, title: '提示'}, function (index) {
//            //do something
//            $.ajax({
//                type: 'post',
//                url: "close_att.do",
//                data: {"id": id},
//                error: function (XMLHttpRequest, textStatus, errorThrown) {
//                    alert(textStatus);
//                },
//                success: function (data) {
//                    if (data.success) {
//                        var message = data.data.message;
//                        if (data.data.type == 'error') {
//                            layer.alert(message);
//                        } else {
//                            layer.alert(message, function (index) {
//                                layer.close(index);
//                            });
//                        }
//                    }
//                }
//            })
//            layer.close(index);
//        });
//
//    }
//
//
//}
/**
 * 修改租户配置时直接跳转到某步
 * */
function step(step) {
    $('#modal-wizard').wizard('selectedItem', {
        step: step
    });
    if(step==2){
        findClientquota();
    }
}

/**
 * 查看租户配置时直接跳转到某步
 * */
function see_step(step) {
    $('#modal-wizard_see').wizard('selectedItem', {
        step: step
    });
    if(step==2){
        findClientquota();
    }
}
/**
 * 新增任务审批流程配置
 * */
function addClusterUser() {
    $.ajax({
        type: 'post',
        url: "add_update_see_clusterUser_wss.do",
        data: {'operate': 'add'},
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        },
        success: function (data) {
            $("#modal-wizard").html(data);

            $('#modal-wizard').modal();
        }
    });
}

function kerbersValidDay(obj) {
    obj.value = obj.value.replace(/\D/g, '')
    var valid = parseInt(obj.value);
    var now = new Date();
    var fDate = formatDate(now);
    $("#start").val(fDate);
    if (valid == 0) {
        $("#end").val('永久');
        $("#loseTime").val('永久');
    } else if (valid > 0) {
        var myDate = now.setDate(now.getDate() + valid);
        var fDate = formatDate(now);
        $("#end").val(fDate);
        $("#loseTime").val(valid);
    } else {
        $("#end").val('');
        $("#loseTime").val('');
    }
}
Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    var week = {
        "0": "\u65e5",
        "1": "\u4e00",
        "2": "\u4e8c",
        "3": "\u4e09",
        "4": "\u56db",
        "5": "\u4e94",
        "6": "\u516d"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[this.getDay() + ""]);
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}
function checkHdfsSpace(obj) {
    var value = $(obj).val();
    if (!/^[0-9]*\.?[0-9]+$/.test(value)) {
        $("#hdfsSpace").val("");
    }
}

/**
 * 校验client配置中的用户目录配置额
 * @param obj
 */
function checkClientQuotaSpace(obj) {
    var value = $(obj).val();
    if (!/^[0-9]*\.?[0-9]+$/.test(value)) {
        $("#clientQuotaSpace").val("");
    }
}
function kerbersValidDay_update(obj) {
    obj.value = obj.value.replace(/\D/g, '')
    var valid = parseInt(obj.value);
    var now = new Date();
    var fDate = formatDate(now);
    $("#start").val(fDate);
    if (valid == 0) {
        $("#end").val('永久');
        $("#loseTime").val('永久');
    } else if (valid > 0) {
        now.setDate(now.getDate() + valid);
        var fDate = formatDate(now);
        $("#end").val(fDate);
        $("#loseTime").val(valid);
    } else {
        $("#end").val('');
        $("#loseTime").val('');
    }
}
function formatDate(now) {
    var year = now.getFullYear();       //年
    var month = now.getMonth() + 1;     //月
    var day = now.getDate();            //日
    var hh = now.getHours();            //时
    var mm = now.getMinutes();          //分
    var ss = now.getSeconds();            //秒
    var clock = year + "-";
    if (month < 10)
        clock += "0";
    clock += month + "-";
    if (day < 10)
        clock += "0";
    clock += day + " ";
    if (hh < 10)
        clock += "0";
    clock += hh + ":";
    if (mm < 10) clock += '0';
    clock += mm+":";
    if (ss < 10) clock += '0';
    clock += mm;
    return clock;
}
$(function () {

//    $('#modal-wizard-container').ace_wizard();
//    $('#modal-wizard .wizard-actions .btn[data-dismiss=modal]').removeAttr('disabled');


})


var userid = '';
var count_index = 1;
//添加li
function addLi_update() {
    //添加li
//    var count = parseInt($("ul li:last input").val());
    var count = count_index;
    var li =
        "<li><a data-toggle='tab' href='#li_" + (count + 1) + "'>" +
        "<span class='save'>*</span><span class='title'>队列配置MR_" + (count + 1) + "</span><span class='close' onclick='closeLi(this, event)'>&times;</span></a>" +
        "<input type='hidden' value='" + (count + 1) + "'/></li>";
    $("#myTab4_update").append(li);
    var index = count + 1;
    //添加li对应的div
    var div = "<div id='li_" + (count + 1) + "' class='tab-pane'>" +
        "<div class='table-responsive'>" +
        "<form id='queue" + index + "'>" +
        "    <input value='' name='id' type='hidden'/>" +
        "    <table  style='font-size: 13px; width: 100%'>" +
        '<input type="hidden" name="username" value="' + userid + '" ' +
        "        <tr>" +
        "            <td class='center' style='width: 20%'>队列名称</td>" +
        "            <td class='center' style='width: 50%'>" +
        "                <input name='queueName' title='队列名称不能为空' style='width: 100%'/>" +
        "            </td>" +
        "        </tr>" +
        "        <tr>" +
        "            <td class='center' style='width: 20%'>最小资源量</td>" +
        "            <td class='center' style='width: 50%'>" +
        "                <input name='minResource' value='102400' title='请填写正确的正整数' onkeyup='checkNumber(this)' style='width: 100%'/>" +
        "            </td>" +

        "           <td class='center' style='width: 10%'>" +
        "               <select >" +
        "                   <option value='M'>M</option>" +
        "               </select>" +
        "           </td>" +
        "           <td class='center' style='width: 10%'>" +
        "                <input name='minCpu' value='25'  onkeyup='checkNumber(this)' title='请填写正确的正整数'/>" +
        "           </td>" +
        "           <td class='center' style='width: 10%'>" +
        "                <select>" +
        "                    <option value='H'>核</option>" +
        "                </select>" +
        "           </td>" +
        "        </tr>" +
        "        <tr>" +
        "            <td class='center' style='width: 20%'>最大资源量</td>" +
        "            <td class='center' style='width: 50%'>" +
        "                <input name='maxResource' value='409600' onkeyup='checkNumber(this)' title='请填写正确的正整数' style='width: 100%'/>" +
        "            </td>" +
        "            <td class='center' style='width: 10%'>" +
        "               <select >" +
        "                   <option value='M'>M</option>" +
        "               </select>" +
        "            </td>" +
        "           <td class='center' style='width: 10%'>" +
        "                <input name='maxCpu' value='100' onkeyup='checkNumber(this)' title='请填写正确的正整数'/>" +
        "           </td>" +
        "           <td class='center' style='width: 10%'>" +
        "                <select>" +
        "                    <option value='H'>核</option>" +
        "                </select>" +
        "           </td>" +
        "        </tr>" +
        "        <tr>" +
        "            <td class='center' style='width: 20%'>最大app数量</td>" +
        "            <td class='center' style='width: 50%'>" +
        "                <input name='maxApp' value='50' onkeyup='checkNumber(this)' title='请填写正确的正整数' style='width: 100%'/>" +
        "            </td>" +
        "        </tr>" +
        "        <tr>" +
        "            <td class='center' style='width: 20%'>权值   </td>" +
        "            <td class='center' style='width: 50%'>" +
        "                <input name='weight' value='1' onkeyup='checkNumber(this)' title='请填写正确的权值格式，最多保留4位小数' style='width: 100%'/>" +
        "            </td>" +
        "        </tr>" +
        "        <tr>" +
        "            <td class='center' style='width: 20%'>权限值   </td>" +
        "            <td class='center' style='width: 50%'>" +
        "                <input name='acl' value='*' style='width: 100%'/>" +
        "            </td>" +
        "        </tr>" +
        "    </table>" +
        "    <button class='btn btn-minier btn-primary' readonly type='button' onclick='save(this)' style='margin-left: 45%'>保存</button>" +
        "    <button class='btn btn-minier btn-primary' type='button' onclick='edit(this)'>编辑</button>" +
        "</form>" +
        "</div>" +
        "</div>";
    $("#tab-content").append(div);

    $("a[href='#li_" + (count + 1) + "']").click();
}

//添加li
function addLi() {
    //添加li
    var count = parseInt($("ul li:last input").val());
    var li =
        "<li><a data-toggle='tab' href='#li_" + (count + 1) + "'>" +
        "<span class='save'>*</span><span class='title'>队列配置MR_" + (count + 1) + "</span><span class='close' onclick='closeLi(this, event)'>&times;</span></a>" +
        "<input type='hidden' value='" + (count + 1) + "'/></li>";
    $("#myTab4").append(li);
    var index = count + 1;
    var operate = $("#operate").val();
    var userName = $("#userName").val().replace(/(^\s*)|(\s*$)/g, "") + "_" + index;
    if (operate == 'add') {
        //添加li对应的div
        var div = "<div id='li_" + (count + 1) + "' class='tab-pane'>" +
            "<div class='table-responsive'>" +
            "<form id='queue" + index + "'>" +
            "    <input value='' name='id' type='hidden'/>" +
            "    <table  style='font-size: 13px; width: 100%'>" +
            " <tr>" +
            "            <td class='center' style='width: 20%'>队列名称</td>" +
            "            <td class='center' style='width: 50%'>" +
            "                <input readonly value='" + userName + "' name='queueName' title='队列名称不能为空' style='width: 100%'/>" +
            "            </td>" +
            "        </tr>" +
            "        <tr>" +
            "            <td class='center' style='width: 20%'>最小资源量</td>" +
            "            <td class='center' style='width: 50%'>" +
            "                <input name='minResource' value='102400' title='请填写正确的正整数' onkeyup='checkNumber(this)' style='width: 100%'/>" +
            "            </td>" +

            "           <td class='center' style='width: 10%'>" +
            "               <select >" +
            "                   <option value='M'>M</option>" +
            "               </select>" +
            "           </td>" +
            "           <td class='center' style='width: 10%'>" +
            "                <input name='minCpu' value='25'  onkeyup='checkNumber(this)' title='请填写正确的正整数'/>" +
            "           </td>" +
            "           <td class='center' style='width: 10%'>" +
            "                <select>" +
            "                    <option value='H'>核</option>" +
            "                </select>" +
            "           </td>" +
            "        </tr>" +
            "        <tr>" +
            "            <td class='center' style='width: 20%'>最大资源量</td>" +
            "            <td class='center' style='width: 50%'>" +
            "                <input name='maxResource' value='409600' onkeyup='checkNumber(this)' title='请填写正确的正整数' style='width: 100%'/>" +
            "            </td>" +
            "            <td class='center' style='width: 10%'>" +
            "               <select >" +
            "                   <option value='M'>M</option>" +
            "               </select>" +
            "            </td>" +
            "           <td class='center' style='width: 10%'>" +
            "                <input name='maxCpu' value='100' onkeyup='checkNumber(this)' title='请填写正确的正整数'/>" +
            "           </td>" +
            "           <td class='center' style='width: 10%'>" +
            "                <select>" +
            "                    <option value='H'>核</option>" +
            "                </select>" +
            "           </td>" +
            "        </tr>" +
            "        <tr>" +
            "            <td class='center' style='width: 20%'>最大app数量</td>" +
            "            <td class='center' style='width: 50%'>" +
            "                <input name='maxApp' value='50' onkeyup='checkNumber(this)' title='请填写正确的正整数' style='width: 100%'/>" +
            "            </td>" +
            "        </tr>" +
            "        <tr>" +
            "            <td class='center' style='width: 20%'>权值   </td>" +
            "            <td class='center' style='width: 50%'>" +
            "                <input name='weight' value='1' onkeyup='checkNumber(this)' title='请填写正确的权值格式，最多保留4位小数' style='width: 100%'/>" +
            "            </td>" +
            "        </tr>" +
            "        <tr>" +
            "            <td class='center' style='width: 20%'>权限值   </td>" +
            "            <td class='center' style='width: 50%'>" +
            "                <input name='acl' value='"+$("#userName").val()+"' style='width: 100%'/>" +
            "            </td>" +
            "        </tr>" +
            "    </table>" +

//        "    <button class='btn btn-minier btn-primary' readonly type='button' onclick='save(this)' style='margin-left: 45%'>保存</button>" +
//        "    <button class='btn btn-minier btn-primary' type='button' onclick='edit(this)'>编辑</button>" +
            "</form>" +
            "</div>" +
            "</div>";
        $("#tab-content").append(div);
    } else {
        var username = $("#userid").val();
        //添加li对应的div
        var div = "<div id='li_" + (count + 1) + "' class='tab-pane'>" +
            "<div class='table-responsive'>" +
            "<form id='queue" + index + "'>" +
            "    <input value='' name='id' type='hidden'/>" +
            "    <table  style='font-size: 13px; width: 100%'>" +
            " <input type='hidden' name='username' value='" + username + "'/>" +
            " <tr>" +
            "            <td class='center' style='width: 20%'>队列名称</td>" +
            "            <td class='center' style='width: 50%'>" +
            "                <input readonly name='queueName' value='" + userName + "' title='队列名称不能为空' style='width: 100%'/>" +
            "            </td>" +
            "        </tr>" +
            "        <tr>" +
            "            <td class='center' style='width: 20%'>最小资源量</td>" +
            "            <td class='center' style='width: 50%'>" +
            "                <input name='minResource' value='102400' title='请填写正确的正整数' onkeyup='checkNumber(this)' style='width: 100%'/>" +
            "            </td>" +

            "           <td class='center' style='width: 10%'>" +
            "               <select >" +
            "                   <option value='M'>M</option>" +
            "               </select>" +
            "           </td>" +
            "           <td class='center' style='width: 10%'>" +
            "                <input name='minCpu' value='25'  onkeyup='checkNumber(this)' title='请填写正确的正整数'/>" +
            "           </td>" +
            "           <td class='center' style='width: 10%'>" +
            "                <select>" +
            "                    <option value='H'>核</option>" +
            "                </select>" +
            "           </td>" +
            "        </tr>" +
            "        <tr>" +
            "            <td class='center' style='width: 20%'>最大资源量</td>" +
            "            <td class='center' style='width: 50%'>" +
            "                <input name='maxResource' value='409600' onkeyup='checkNumber(this)' title='请填写正确的正整数' style='width: 100%'/>" +
            "            </td>" +
            "            <td class='center' style='width: 10%'>" +
            "               <select >" +
            "                   <option value='M'>M</option>" +
            "               </select>" +
            "            </td>" +
            "           <td class='center' style='width: 10%'>" +
            "                <input name='maxCpu' value='100' onkeyup='checkNumber(this)' title='请填写正确的正整数'/>" +
            "           </td>" +
            "           <td class='center' style='width: 10%'>" +
            "                <select>" +
            "                    <option value='H'>核</option>" +
            "                </select>" +
            "           </td>" +
            "        </tr>" +
            "        <tr>" +
            "            <td class='center' style='width: 20%'>最大app数量</td>" +
            "            <td class='center' style='width: 50%'>" +
            "                <input name='maxApp' value='50' onkeyup='checkNumber(this)' title='请填写正确的正整数' style='width: 100%'/>" +
            "            </td>" +
            "        </tr>" +
            "        <tr>" +
            "            <td class='center' style='width: 20%'>权值   </td>" +
            "            <td class='center' style='width: 50%'>" +
            "                <input name='weight' value='1' onkeyup='checkNumber(this)' title='请填写正确的权值格式，最多保留4位小数' style='width: 100%'/>" +
            "            </td>" +
            "        </tr>" +
            "        <tr>" +
            "            <td class='center' style='width: 20%'>权限值   </td>" +
            "            <td class='center' style='width: 50%'>" +
            "                <input name='acl' value='*' style='width: 100%'/>" +
            "            </td>" +
            "        </tr>" +
            "    </table>" +

            "    <button class='btn btn-minier btn-primary' readonly type='button' onclick='save(this)' style='margin-left: 45%'>保存</button>" +
            "    <button class='btn btn-minier btn-primary' type='button' onclick='edit(this)'>编辑</button>" +
            "</form>" +
            "</div>" +
            "</div>";
        $("#tab-content").append(div);
    }


    $("a[href='#li_" + (count + 1) + "']").click();
}

// 关闭li
function closeLi(obj, event) {
    layer.confirm('确定是否移除?', {icon: 3, title: '提示'}, function (index) {
        //do something
        var flag = true;
        var $a = $(obj).parents('a');
        var $li = $a.parent();
        var href = $a.attr("href");
        //后面的计数减1
        var count = parseInt(href.split("_")[1]);
        $("a[href='#li_" + (count - 1) + "']").click();
        //下一个li节点
        var $liNext = $li.next();
        //数据库删除
        var id = $(href).find("input[name='id']").val();
//        alert(id);
        if (id != "") {
            $.ajax({
                url: "user/del_queue.do",
                data: "id=" + id,
                type: "post",
                dataType: "json",
                async: false,
                success: function (data) {
//                    alert(data);
                    var ErrorMessage = data.ErrorMessage;
                    if (data.success == "success") {
                        if (ErrorMessage != null && ErrorMessage.length > 0) {
                            ErrorMessage = "刪除成功,同步队列信息失败[" + ErrorMessage + "]";
                            alert(ErrorMessage);
                        } else {
                            alert("删除成功");
                            count_index = count_index - 1;
                        }
                    }
                },
                error: function () {
                    alert("error");
                }
            })
        }
        //页面删除
        $li.remove();
        $(href).remove();


        while (flag) {
            if ($liNext.length > 0) {
                var $aNext = $liNext.find('a');
                var $inputNext = $aNext.next();
                var hrefNext = $aNext.attr("href");
                var countNext = parseInt(hrefNext.split("_")[1]) - 1;
                $(hrefNext).attr('id', 'li_' + countNext)
                $aNext.attr('href', '#li_' + countNext);
                $inputNext.val(countNext);
                $aNext.find("span.title").html("队列配置MR_" + countNext);
                $liNext = $liNext.next();
            } else {
                flag = false;
            }
        }
        event.stopPropagation();
        layer.close(index);
    });

}


function kerberidCheck(obj,clusterMachineId) {
    /*var kerberid = $("#kerberid").val();
    var kid = obj.value;
    var kidList = [];
    if (obj.checked) {
        *//*if(kerberid!=""&&kerberid!=null){
            kidList.push(kerberid);
        }*//*
        kidList.push(kid);
        $("#kerberid").val(kidList.toString());
    } else {
        var reg = new RegExp(kid, "g"); //创建正则RegExp对象
        var newstr = kerberid.replace(reg, "");
        $("#kerberid").val(newstr);
    }
*/
    var kerberid = "";
    var machineId = document.getElementsByName("machineId");
    var machineIds = [];
    for (var i = 0; i < machineId.length; i++) {
        if (machineId[i].checked) {
            machineIds.push(machineId[i].value);
        }
    }
    $("#kerberid").val(machineIds.toString());
    kerberid = machineIds.toString();
    if(kerberid != ""){
        $("#kerberid-error").hide();
    }

    if (obj.checked) {
        if($("#kerbers_tr_"+clusterMachineId).find("input[id='clientquotaId']").val() && ""!=$("#kerbers_tr_"+clusterMachineId).find("input[id='clientquotaId']").val()  ){
            $("#kerbers_tr_"+clusterMachineId).find("select[id='clientCatalog']").attr("disabled",true);
        }else{
            $("#kerbers_tr_"+clusterMachineId).find("select[id='clientCatalog']").removeAttr("disabled");
        }

        $("#kerbers_tr_"+clusterMachineId).find("input[id='clientCatalogSize']").removeAttr("disabled");
        $("#kerbers_tr_"+clusterMachineId).find("select[id='clientCatalogUnit']").removeAttr("disabled");
    }else{
        $("#kerbers_tr_"+clusterMachineId).find("select[id='clientCatalog']").attr("disabled",true);
        $("#kerbers_tr_"+clusterMachineId).find("input[id='clientCatalogSize']").attr("disabled",true);
        $("#kerbers_tr_"+clusterMachineId).find("select[id='clientCatalogUnit']").attr("disabled",true);
    }


    var machineId = document.getElementsByName("machineId");
    var machineIds = [];
    var machineClientQuotaList = "";
    for (var i = 0; i < machineId.length; i++) {
        if (machineId[i].checked) {
            machineIds.push(machineId[i].value);
            var client = {
                "clientCatalog":$("#kerbers_tr_"+machineId[i].value).find("select[id='clientCatalog']").val(),
                "clientCatalogSize":$("#kerbers_tr_"+machineId[i].value).find("input[id='clientCatalogSize']").val(),
                "clientCatalogUnit":$("#kerbers_tr_"+machineId[i].value).find("select[id='clientCatalogUnit']").val()
            }
            machineClientQuotaList += client + ";";
        }
    }

    console.log(machineClientQuotaList);
    console.log(machineClientQuotaList.toString());
}

//判断数组中是否有重复的
function checkArrayRepeat(obj) {
    var nary = obj.sort();
    for (var i = 0; i < nary.length; i++) {
        if (nary[i] == nary[i + 1]) {
            return true;
        }

    }
}
//
function checkNumber(obj) {
    obj.value = obj.value.replace(/\D/g, '')
}

//function updateClusterUser(operate) {
//    var userIdList = document.getElementsByName("id");
//    var userIds = "";
//    if (userIdList.length > 0) {
//        for (var i = 0; i < userIdList.length; i++) {
//            if (userIdList[i].checked) {
//                userIds += userIdList[i].value + ",";
//            }
//        }
//        userIds = userIds.substring(0, userIds.length - 1);
//    }
//    if (userIds.trim() == "") {
//        layer.alert('请选择一条数据!');
//    } else {
//        $.ajax({
//            type: 'post',
//            url: "add_update_see_clusterUser_wss.do",
//            data: {"userIds": userIds, 'operate': operate},
//            error: function (XMLHttpRequest, textStatus, errorThrown) {
//                alert(textStatus);
//            },
//            success: function (data) {
//                $("#modal-wizard").html(data);
//                $('#modal-wizard').wizard();
//                $('#modal-wizard').modal();
//                $("#clusterUser").find('input').attr("readonly", true);
//                $("#clusterUser").find('select').attr("disabled", true);
//                $("#kerbers_form").find('input').attr("disabled", true);
//                $("#hdfsquota_form").find('input').attr("readonly", true);
//                $("#hdfsquota_form").find('select').attr("disabled", true);
//                $("#clientquota_form").find('input').attr("readonly", true);//add20160714qinfengxia
//                $("#clientquota_form").find('select').attr("disabled", true);//add20160714qinfengxia
//                $("#remark").attr("readonly", true);
//            }
//        })
//    }
//}


function updateClusterUser(operate) {
    var userIds = selectedUsers();
    if (userIds.trim() == "" ) {
        layer.alert('请选择一条数据!');
    }else {
        var userList = userIds.split(",");
        if(userList.length==1){
            $.ajax({
                type: 'post',
                url: "add_update_see_clusterUser_wss.do",
                data: {"userIds": userIds, 'operate': operate},
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(textStatus);
                },
                success: function (data) {
                    $("#modal-wizard").html(data);
                    $('#modal-wizard').wizard();
                    $('#modal-wizard').modal();
                    $("#clusterUser").find('input').attr("readonly", true);
                    $("#clusterUser").find('select').attr("disabled", true);
                    $("#kerbers_form").find('input').attr("disabled", true);
                    $("#hdfsquota_form").find('input').attr("readonly", true);
                    $("#hdfsquota_form").find('select').attr("disabled", true);
                    $("#clientquota_form").find('input').attr("readonly", true);//add20160714qinfengxia
                    $("#clientquota_form").find('select').attr("disabled", true);//add20160714qinfengxia
                    $("#remark").attr("readonly", true);
                }
            })
        }else{
            layer.alert('目前选择多条数据，请点击批量修改按钮!');
        }

    }

}

/*获取选中的users*/
function selectedUsers(){
    var userIdList = document.getElementsByName("id");
    var userIds = "";
    if (userIdList.length > 0) {
        for (var i = 0; i < userIdList.length; i++) {
            if (userIdList[i].checked) {
                userIds += userIdList[i].value + ",";
            }
        }
        userIds = userIds.substring(0, userIds.length - 1);
    }
    return userIds;
}

function batchUpdateClusterUser(){
    var userIds = selectedUsers();
    if (userIds.trim() == "" || (userIds.trim() != "" && userIds.split(",").length == 0 )) {
        layer.alert('请至少选择一条数据!');
        return;
    }
    thirdWin.init({title:'批量修改',rel:''}).show('query_batch_update_clusterUser_pop.do?userIds='+userIds,{})
}

var isEdit = 0;
//-----------------------编辑Mr
function edit(obj) {
    //更新数据,队列名不需要进行验证
    isEdit = 1;
    var $div = $(obj).parent().parent().parent();
    var id = $div.attr('id');
    var $span = $("a[href='#" + id + "']").find('span');
    $span.show();

    var $table = $(obj).prev().prev();
    $table.find('input').removeAttr("readonly");
    var $save = $(obj).prev();
    $save.removeAttr("disabled");
    $("input[name='queueName']").attr("readonly", true);
    $("input[name='queue']").attr("readonly", true);
}
/**
 * 保存Mr
 * @param obj
 */
function save(obj) {
    //可以
    var $div = $(obj).parent().parent().parent();
    var id = $div.attr('id');
    var $span = $("a[href='#" + id + "']").find('span.save');
    var $table = $(obj).prev();

    //表单提交验证
    var number = /^\+?[1-9][0-9]*$/;
    var float = /^\+?[1-9][0-9]*(.[0-9]{0,4})?$/;
    var minResource = $(obj).prev().find("input[name='minResource']").val();
    var minCpu = $(obj).prev().find("input[name='minCpu']").val();
    var maxResource = $(obj).prev().find("input[name='maxResource']").val();
    var maxCpu = $(obj).prev().find("input[name='maxCpu']").val();
    var maxApp = $(obj).prev().find("input[name='maxApp']").val();
    var weight = $(obj).prev().find("input[name='weight']").val();

    //队列名称检查
    var flag = true;
    if ($(obj).prev().find("input[name='queueName']").val() == "") {
        var tooltip = $(obj).prev().find("input[name='queueName']").tooltip();
        tooltip.tooltip("open");
        return false;
    } else {
        if (isEdit == 1) {
            var queueName = $(obj).prev().find("input[name='queueName']").val();
            var usename = $(obj).prev().find("input[name='username']").val();
            var fid = $(obj).prev().find("input[name='id']").val();
            $.ajax({
                url: "check_queue.do",
                data: {"queueName": queueName, "userId": usename, "id": fid},
                type: "post",
                async: false,
                dataType: "text",
                success: function (data) {
                    if (data == "yes") {
                        alert("队列名称已存在,请更换队列名");
                    } else {
                        flag = false;
                    }
                },
                error: function () {

                    alert("error")
                }
            })
        } else {
            flag = false;
        }
    }
    if (flag) {
        return false;
    }
    //最小值最大值配置
    if (minResource == "" || !(number.test(minResource))) {
        var tooltip = $(obj).prev().find("input[name='minResource']").tooltip();
        tooltip.tooltip("open");
        return false;
    }

    if (minCpu == "" || !(number.test(minCpu))) {
        var tooltip = $(obj).prev().find("input[name='minCpu']").tooltip();
        tooltip.tooltip("open");
        return false;
    }

    if (maxResource == "" || !(number.test(maxResource))) {
        var tooltip = $(obj).prev().find("input[name='maxResource']").tooltip();
        tooltip.tooltip("open");
        return false;
    }

    if (maxCpu == "" || !(number.test(maxCpu))) {
        var tooltip = $(obj).prev().find("input[name='maxCpu']").tooltip();
        tooltip.tooltip("open");
        return false;
    }

    if (parseInt(minResource) > parseInt(maxResource)) {
        alert("最小资源不能大于最大资源数")
        return false;
    }

    if (parseInt(minCpu) > parseInt(maxCpu)) {
        alert("最小资源CPU不能大于最大资源CPU数")
        return false;
    }

    //最大app数
    if (maxApp == "" || !(number.test(maxApp))) {
        var tooltip = $(obj).prev().find("input[name='maxApp']").tooltip();
        tooltip.tooltip("open");
        return false;
    }
    //权值判断
    if (weight == "" || !(float.test(weight))) {
        var tooltip = $(obj).prev().find("input[name='weight']").tooltip();
        tooltip.tooltip("open");
        return false;
    }


    var $form = $(obj).parent();
    var userId = $(obj).prev().find("input[name='username']").val();
    $.ajax({
        url: "save_queue.do?userId=" + userId,
        data: $form.serializeArray(),
        type: "post",
        dataType: "json",
        success: function (json) {
            //得到
            //var map = (json["data"]);
            //var ErrorMessage = map.ErrorMessage;
            //if (map.fairSchedulerAllocation1 != null) {
            //    var id = map.fairSchedulerAllocation1.id;
            //    //prev()上一个同级元素
            //    $(obj).prev().prev().val(id);
            //}
            ////如果出现错误信息,进行提示
            //if (ErrorMessage != null && ErrorMessage.length > 0) {
            //    //保存成功,同步队列信息失败,参数清除
            //    $(obj).prev().find("input[name='username']").val();
            //    alert(ErrorMessage);
            //} else {
            //新建成功
            //保存操作
            var id = json.data;
            console.log(id);
            $(obj).prev().prev().val(id);
            $span.hide();
            $table.find('input').attr("readonly", true);
            $(obj).attr("disabled", true);
            alert("保存成功");
            //}
        },
        error: function () {
            alert("保存不成功!");
        }
    });
    //保存完后还原isEdit
    isEdit = 0;
    count_index += 1;
//    userid = '';
}
//----------------编辑clusterUser
function editClusterUser() {
    $("#clusterUser").find('input').attr("readonly", false);
    $("#clusterUser").find('select').attr("disabled", false);
    $("#remark").attr("readonly", false);
    $("#userName").attr("readonly", true);
    $("#clientPW").attr("readonly", true);
    $("#clusterTypeId").attr("disabled", true);
    $("#hp_update").attr("disabled", false);
}
//-----------------验证clusterUser
//----------------修改clusterUser
function saveClusterUser() {
    var clusterTypeId = $("#clusterTypeId").val();
    $.ajax({
        type: 'post',
        url: "update_clusterUser_byId.do?clusterTypeId=" + clusterTypeId,
        data: $("#clusterUser").serialize(),
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
            var hdfs = "";
        },
        success: function (data) {
            if (data.success) {
                layer.alert(data.data, {maxWidth: 630}, function (index) {
                    $("#hp_update").attr("disabled", true);
                    $("#clusterUser").find('input').attr("readonly", true);
                    $("#clusterUser").find('select').attr("disabled", true);
                    $("#remark").attr("readonly", true);
                    layer.close(index);
                });
            }
        }
    })
}
//---------------------编辑kerbers
function editKerbers() {
    $("#days").attr("disabled", false);
    $("#kerbers_form").find("input[name=machineId]").attr("disabled", false);
    $("#kerbers_form").find("input[id=checkAll]").attr("disabled", false);
    $("#kerbers_form").find("button").attr("disabled", false)
    $("#status").attr("disabled", false);
    $("#open").attr("disabled", true);
    $("#close").attr("disabled", true);
    $("#kerbers_table").find(":checkbox:checked").each(function(){
        $("#kerbers_tr_"+$(this).val()).find("select[id='clientCatalog']").attr("disabled",true);
        $("#kerbers_tr_"+$(this).val()).find("input[id='clientCatalogSize']").removeAttr("disabled");
        $("#kerbers_tr_"+$(this).val()).find("select[id='clientCatalogUnit']").removeAttr("disabled");
    });
}
//----------------修改kerbers
function updateKerbers() {
    //验证
    var form = document.forms['kerbers_form'];
    var $form = $(form);
    var flag = ($form).valid($form);
    if (!flag) {
        return;
    }
    //----------------kerbers配置
    var days = $("#days").val();
    var status = $("#status:checked").val();
    if (status == 'on') {
        status = 0;//0为成功
    } else {
        status = 1;//1为不成功
    }
    var kerberid = $("#kerber_id_update").val();
    var machineId = $("#kerbers_form").find("input[name=machineId]");
    var start = $("#start").val();
    var end =$("#end").val();
    var startTime = 0;
    var endTime = 0;
    if(start!='永久'){
        startTime=start;
    }
    if(end!='永久'){
        endTime = end;
    }

    //获取多选时的
    var ids = $("#ids").val();
    var machineIds = [];
    var machineClientQuotaList = "";
    for (var i = 0; i < machineId.length; i++) {
        if (machineId[i].checked) {
            machineIds.push(machineId[i].value);
            var clientquotaId = $("#kerbers_tr_"+machineId[i].value).find("input[id='clientquotaId']").val();
            var clientCatalog = $("#kerbers_tr_"+machineId[i].value).find("select[id='clientCatalog']").val();
            var clientCatalogSize = $("#kerbers_tr_"+machineId[i].value).find("input[id='clientCatalogSize']").val();
            var clientCatalogUnit = $("#kerbers_tr_"+machineId[i].value).find("select[id='clientCatalogUnit']").val();
            if(clientCatalogSize == "" || clientCatalogSize == null){
                clientCatalogSize = 0 ;
            }
            var client = "";
            if(null != clientquotaId && "" != clientquotaId){
                client = '{"id":' + clientquotaId + ',"machineId":' + machineId[i].value + ',"clientCatalog":"' + clientCatalog + '", "clientCatalogSize":' + clientCatalogSize + ', "clientCatalogUnit":"' + clientCatalogUnit + '"}';
            }else{
                client = '{"machineId":' + machineId[i].value + ',"clientCatalog":"' + clientCatalog + '", "clientCatalogSize":' + clientCatalogSize + ', "clientCatalogUnit":"' + clientCatalogUnit + '"}';
            }
            machineClientQuotaList += client + ";";
        }
    }
    if (machineIds.length == 0) {
        alert("请至少选择一台机器!");
        return;
    }
    var userId = $("#userid").val();
    $.ajax({
        type: 'post',
        url: "update_kerbers_byId.do",
        data: {
            "id": kerberid,
            "validDay": days,
            "userId": userId,
            "status": status,
            "machineIds": machineIds.toString(),
            "userIds": ids,
            "start":startTime,
            "end":endTime,
            "machineClientQuotaList":machineClientQuotaList.toString()
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        },
        success: function (data) {
            var message = data.data.message;
            if (data.data.type == 'error') {
                var message = data.data.message;
                layer.alert(message, {maxWidth: 630});
            } else {
                if (message != undefined) {
                    var messagebr = message.replace(/, /g, '<br/>');
                    layer.alert(messagebr, {maxWidth: 630}, function (index) {
                        var operate = $("#operate").val();
                        //updateClusterUser(operate);
                        $("#ker_up").attr("disabled", true);
                        $("#kerbers_form").find('input').attr("disabled", true);
                        layer.close(index);
                    });
                } else {
                    layer.alert("kerbers配置修改失败");
                }
            }
        }
    })
}
//----------------------查看租户配置
//---------------编辑Hdfs
function editHdfs() {
    $("#hdfsquota_form").find('input').attr("readonly", false);
    $("#hdfsquota_form").find('select').attr("disabled", false);
    $("#hdfsquota_form").find("input").attr("disabled", false);
    $("#up_hdfsquota").removeAttr("disabled");
}
//-------------------修改Hdfs
function updateHdfs() {
    var id = $("#hdfsquota_id").val();
    var hdfsSpace = $("#hdfsSpace").val();
    var hdfsFileCount = $("#hdfsFileCount").val();
    var hdfsSpaceUnit = $("#hdfsSpaceUnit").val();
    if (hdfsSpace == "") {
        hdfsSpace = null;
    }
    if (hdfsFileCount == "") {
        hdfsFileCount = null;
    }
    var hdfs = "";
    //if(hdfsSpace != null || hdfsFileCount != null){
    //    hdfs +=  '{';
    //}
    //if(hdfsSpace!=null){
    //    hdfs += '"hdfsSpace":'+hdfsSpace;
    //}
    //if(hdfsFileCount!=null){
    //    hdfs += ',"hdfsFileCount":' + hdfsFileCount;
    //}
    //if(hdfsSpace != null || hdfsFileCount != null){
    //    hdfs += ',"hdfsSpaceUnit":"' + hdfsSpaceUnit + '"}';
    //}
    if (hdfsSpace != null || hdfsFileCount != null) {
        hdfs = '{"id": "' + id+ '","hdfsSpace":"' + hdfsSpace + '","hdfsFileCount":"' + hdfsFileCount + '","hdfsSpaceUnit":"' + hdfsSpaceUnit + '"}';
    }
    //获取userIds
    var userIdList = document.getElementsByName("id");
    var userIds = "";
    if (userIdList.length > 0) {
        for (var i = 0; i < userIdList.length; i++) {
            if (userIdList[i].checked) {
                userIds += userIdList[i].value + ",";
            }
        }
        userIds = userIds.substring(0, userIds.length - 1);
    }
    //var hpUser_id = $("#userid").val();
    $.ajax({
        type: 'post',
        url: "update_hdfs_byId.do",
        data: {"hdfs": hdfs, "userIds": userIds},
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        },
        success: function (data) {
            var message = data.data.message;
            if (!data.success) {
                var message = data.message;
                layer.alert(message, {maxWidth: 630});
            } else {
                var messagebr = message.replace(/, /g, '<br/>');
                $("#up_hdfsquota").attr("disabled", true);
                $("#hdfsquota_form").find('input').attr("readonly", true);
                $("#hdfsquota_form").find('select').attr("disabled", true);
                layer.alert(messagebr, {maxWidth: 630}, function (index) {
                    var operate = $("#operate").val();
                    layer.close(index);
                });
            }
        }
    })
}
/*编辑client  add20160715qinfengxia */
function editClientquota() {
    $("#clientquota_form").find('input').attr("readonly", false);
     $("#clientquota_form").find('select').attr("disabled", false);
     $("#clientquota_form").find("input").attr("disabled", false);
     $("#up_clientquota").removeAttr("disabled");
}

/*保存client   add20160715qinfengxia*/
function updateClient() {
    var id = $("#clientquota_id").val();
    var clientCatalog = $("#clientCatalog").val();
    var clientCatalogSize = $("#clientCatalogSize").val();
    var clientCatalogUnit = $("#clientCatalogUnit").val();
    if (clientCatalog == "") {
        clientCatalog = null;
    }
    if (clientCatalogSize == "") {
        clientCatalogSize = null;
    }
    var client = "";
    if (clientCatalog != null || clientCatalogSize != null) {
        client = '{"id": "' + id+ '","clientCatalog":"' + clientCatalog + '","clientCatalogSize":"' + clientCatalogSize + '","clientCatalogUnit":"' + clientCatalogUnit + '"}';
    }
    //获取userIds
    var userIdList = document.getElementsByName("id");
    var userIds = "";
    if (userIdList.length > 0) {
        for (var i = 0; i < userIdList.length; i++) {
            if (userIdList[i].checked) {
                userIds += userIdList[i].value + ",";
            }
        }
        userIds = userIds.substring(0, userIds.length - 1);
    }
    $.ajax({
        type: 'post',
        url: "update_client_byId.do",
        data: {"client": client, "userIds": userIds},
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        },
        success: function (data) {
            var message = data.data.message;
            if (!data.success) {
                var message = data.message;
                layer.alert(message, {maxWidth: 630});
            } else {
                var messagebr = message.replace(/, /g, '<br/>');
                $("#up_clientquota").attr("disabled", true);
                $("#clientquota_form").find('input').attr("readonly", true);
                $("#clientquota_form").find('select').attr("disabled", true);
                layer.alert(messagebr, {maxWidth: 630}, function (index) {
                    var operate = $("#operate").val();
                    layer.close(index);
                });
            }
        }
    })
}
function cancelUpdate() {
    var operate = $("#operate").val();
    if (operate == 'update') {
        var hp_update = $("#hp_update");
        var hpAttr = hp_update.attr("disabled");
        if (hp_update.length != 0 && hpAttr == undefined) {
            if(confirm("租户配置没有保存,是否进行保存?")){
                return;
            }
        }
        var hdfs = $("#up_hdfsquota").attr("disabled");
        if (hdfs == undefined) {
            if (confirm("HDFS配置没有保存,是否进行保存?")) {
                return;
            }
        }
        var ker_up = $("#ker_up").attr("disabled");
        if (ker_up == undefined) {
            if (confirm("Kerbers配置没有保存,是否进行保存")) {
                return;
            }
        }
    }
    window.location.reload();
}
